{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import win32com.client\n",
    "from win32com.client import Dispatch\n",
    "import os\n",
    "import numpy as np\n",
    "from pyDOE import lhs\n",
    "from scipy.stats.distributions import norm\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "from sklearn import ensemble\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import mean_squared_error,mean_absolute_percentage_error,mean_absolute_error #MSE\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "base_path = os.getcwd()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## part1 接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 建立连接\n",
    "def open_simulation(path,visible=True):\n",
    "    unisim = win32com.client.Dispatch('UniSimDesign.Application')\n",
    "    unisim.Visible = visible\n",
    "    simcase = unisim.SimulationCases.Open(path)\n",
    "    return simcase"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 获取输入表中可以操作的接口的集合，返回以列表的形式\n",
    "def get_cells_list(operation_name):\n",
    "    operation = f.Operations(operation_name)\n",
    "    cells_list = []\n",
    "    for i in range(1,operation.NumberOfRows):\n",
    "        variable_number = 'A'+str(i)\n",
    "        variable = operation.Cell(variable_number)\n",
    "        variable_value = variable.CellVariable()\n",
    "        if(variable_value==-32767.0):break\n",
    "        cells_list.append(variable)\n",
    "    return cells_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 获取输入表cells_list中的所有的值，值的名字和单位\n",
    "def get_cells_value(cells_list,unit_list):\n",
    "    value_list = []\n",
    "    flag = False\n",
    "    for index,cell in enumerate(cells_list):\n",
    "        cell_value = cell.CellVariable.GetValue(unit_list[index])\n",
    "        value_list.append(cell_value)\n",
    "        if(cell_value==-32767.0):\n",
    "            flag = True\n",
    "    if(flag):\n",
    "        simcase.Close()\n",
    "        recover_init()\n",
    "    return value_list\n",
    "def get_cells_name(cells_list):\n",
    "    name_list = []\n",
    "    unit_list = []\n",
    "    for cell in cells_list:\n",
    "        cell_name = cell.AttachedObjectName+' '+cell.VariableName+' '+cell.Units\n",
    "        name_list.append(cell_name)\n",
    "        unit_list.append(cell.Units)\n",
    "    return name_list,unit_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 获得需要获得的输出的值\n",
    "def get_outputs_value(outputs_cells_list):\n",
    "    value_list = []\n",
    "    flag = False\n",
    "    for cell in outputs_cells_list:\n",
    "        stream = f.Streams(cell)\n",
    "        temperature = stream.Temperature.GetValue('C')\n",
    "        pressure = stream.Pressure.GetValue('kpa')\n",
    "        mole_flow = stream.MolarFlow.GetValue('kgmole/h')\n",
    "        frac = stream.ComponentMolarFraction.Values\n",
    "        value_list.append(temperature)\n",
    "        value_list.append(pressure)\n",
    "        value_list.append(mole_flow)\n",
    "        for i in frac:\n",
    "            value_list.append(i)\n",
    "        if(temperature==-32767.0):\n",
    "            flag = True\n",
    "    if(flag):\n",
    "        simcase.Close()\n",
    "        recover_init()\n",
    "    return value_list\n",
    "\n",
    "# 获得需要获得的输出的名字\n",
    "def get_outputs_name(outputs_cells_list):\n",
    "    name_list = []\n",
    "    for cell in outputs_cells_list:\n",
    "        names = [\"Temperature(C)\",\"Pressure\",\"mole_flow(kgmole/h)\",\n",
    "        \"MethaneFrac\",\"H2OFrac\",\"COFrac\",\"CO2Frac\",\"H2Frac\",\"N2Frac\",\n",
    "        \"O2Frac\",\"AmmoniaFrac\",\"ArgonFrac\"]\n",
    "        for name in names:\n",
    "            name_list.append(cell+name)\n",
    "    return name_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 用于设置input中的变量的值\n",
    "def set_cells_value(set_value,unit_list):\n",
    "    cells_list = get_cells_list('INPUTS')\n",
    "    assert len(cells_list)==len(set_value)\n",
    "    for index,cell in enumerate(cells_list):\n",
    "        cell.CellVariable.SetValue(set_value[index],unit_list[index])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 采样及数据生成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Gen_labels():\n",
    "    def __init__(self,n,samples,initial,rate=0.05,is_norm=False):\n",
    "        self.xlim = [[0,2*initial[0]],[initial[1]*(1-0.05),initial[1]*(1+0.05)],[initial[2]*(1-0.05),initial[2]]]\n",
    "        self.n = n\n",
    "        self.samples = samples\n",
    "        self.l = None\n",
    "        self.is_normal = is_norm\n",
    "        \n",
    "    def lhs_sampling(self):\n",
    "        self.l = lhs(self.n,self.samples)\n",
    "        if(self.is_normal):\n",
    "            self.l = norm(loc=0,scale=1).ppf(self.l)\n",
    "            \n",
    "    def compute(self):\n",
    "        print(self.xlim)\n",
    "        scaling = np.array([x[1]-x[0] for x in self.xlim])  # 距离放缩\n",
    "        translation = np.array([self.xlim[i][0]/scaling[i] for i in range(self.n)]) # 距离平移\n",
    "        self.lhs_sampling()\n",
    "        self.l = (self.l+translation)*scaling\n",
    "        return self.l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gen_data(input_dims,num,initial_input_value,random_seed=10086):\n",
    "    \"\"\"\n",
    "    input_dims:输入特征的数量\n",
    "    num:生成样本点的个数\n",
    "    \"\"\"\n",
    "    np.random.seed(random_seed)\n",
    "    gen = Gen_labels(input_dims,num,initial_input_value) # 100×3\n",
    "    data_list = gen.compute()\n",
    "    output = []\n",
    "    for i in tqdm(range(num)):\n",
    "        # 设置输入\n",
    "        set_cells_value(data_list[i],input_unit_list)\n",
    "        # 读取输出\n",
    "        output.append(get_outputs_value(outputs_cell))\n",
    "    return data_list,np.array(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def save_data(inputs,outputs,filename):\n",
    "    inputs_data = pd.DataFrame(data=inputs, columns=input_name_list)\n",
    "    outputs_data = pd.DataFrame(data=outputs, columns=output_name_list)\n",
    "    path1 = os.path.join('results',filename[0])\n",
    "    path2 = os.path.join('results',filename[1])\n",
    "    inputs_data.to_csv(path1)\n",
    "    outputs_data.to_csv(path2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def recover_init():\n",
    "    global simcase,f,inputs_cell,outputs_cell,input_name_list,input_unit_list,output_name_list,initial_input_value,initial_out_value\n",
    "    simcase = open_simulation(os.path.join(base_path,file_name),True)\n",
    "    f = simcase.Flowsheet\n",
    "\n",
    "    inputs_cell = get_cells_list('INPUTS')\n",
    "    \n",
    "\n",
    "    input_name_list,input_unit_list = get_cells_name(inputs_cell)\n",
    "    output_name_list = get_outputs_name(outputs_cell)\n",
    "\n",
    "    initial_input_value = get_cells_value(inputs_cell,input_unit_list) # [1.8, 7200.0, 712.0, 0.4]\n",
    "    initial_out_value = get_outputs_value(outputs_cell) # [4372.139378169529, 23500.672485838364]\n",
    "\n",
    "    print(initial_input_value,initial_out_value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO:对于压力，增加进料时的压力的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[762.1721221210902, 0.4753241687125101, 7814.899999999991] [1.8, 3185.0, 7814.899999999991, 0.0, 0.0, 0.0, 0.0, 0.7484748474847485, 0.2496249624962496, 0.0, 0.0, 0.0019001900190019003, 440.71389074126466, 15252.17212212109, 23845.47532840609, 0.00022801703236441224, 0.0, 0.0, 0.0, 0.5821682802013423, 0.19421017046061848, 0.0, 0.19477383335025647, 0.02861969895541827, 59.75224035388362, 15272.17212212109, 27524.23260007846, 0.00019754136650067616, 0.0, 0.0, 0.0, 0.7048414885540643, 0.23508070076835988, 0.0, 0.03508574242040018, 0.02479452689067489, 105.37485965851278, 7897.0, 68.66739992153012, 0.0, 0.0, 0.0, 0.0, 0.7484748474847485, 0.2496249624962496, 0.0, 0.0, 0.0019001900190019003, 2.737496122557161, 1581.0, 40.76124266722513, 0.0002531355503200314, 6.955781832062915e-43, 0.0, 0.0, 0.5036061435463486, 0.1846501027834059, 0.0, 0.28615314228946437, 0.02533747583046112, 4.148433451247854, 1581.0, 4.221556762977376, 0.00022065196961682074, 6.716155369116182e-42, 0.0, 0.0, 0.44860001710625036, 0.20750422737795687, 0.0, 0.32843604180759894, 0.015239061738576948, 0.9682609609015458, 14899.0, 366.43107405687243, 0.0002693442181063608, 0.0, 0.0, 0.0, 0.6880915943717771, 0.2295115025572585, 0.0, 0.04830506696682428, 0.03382249188603367, 104.03697458830317, 1605.0, 2396.6760407870843, 4.80206155587093e-07, 0.0, 0.0, 0.0, 0.000488675490828406, 0.00022948939830947217, 0.0, 0.9992477514433032, 3.360346140319507e-05, 3.556080711556774, 1862.0, 560.7118828594995, 5.462834185500617e-07, 0.0, 0.0, 0.0, 0.0006090442050618982, 0.00027414551786862596, 0.0, 0.9990761455117988, 4.0118481852120566e-05, 3.556080711556774, 1862.0, 3103.7926855854685, 5.462834185500617e-07, 0.0, 0.0, 0.0, 0.0006090442050618982, 0.00027414551786862596, 0.0, 0.9990761455117988, 4.0118481852120566e-05, 3.6306971104525587, 1600.0, 2396.6760407870843, 4.801688286633881e-07, 0.0, 0.0, 0.0, 0.0004886369394514085, 0.00022947128757485585, 0.0, 0.9992478107387096, 3.360086543545036e-05, 14.940582503145322, 721.0, 1350.47704571187, 8.461601682901345e-07, 0.0, 0.0, 0.0, 0.0008666448971788129, 0.0004070526627719809, 0.0, 0.9986664021924148, 5.905408746619142e-05, 29.982170704486123, 14800.0, 19778.0, 0.00027491022953291325, 0.0, 0.0, 0.0, 0.6877520888473301, 0.2293843091038512, 0.0, 0.048827390804203376, 0.033761301015082394, 52.85020299594731, 4097.0, 379.472220840516, 0.00028731646220370345, 0.004279631688246938, 0.0, 0.0, 0.7185873489939062, 0.24145074052022492, 0.0, 8.991425342641614e-06, 0.03538597091007561, 39.92098000069575, 2600.0, 54.6696946155967, 2.898333323859718e-07, 4.393820122697272e-05, 0.0, 0.0, 9.574664678103657e-05, 3.8621036474379034e-05, 0.0, 0.9997989663970149, 2.2437885170264664e-05, 39.92098000069575, 2600.0, 3686.4219006585386, 2.898333323859718e-07, 4.393820122697272e-05, 0.0, 0.0, 9.574664678103657e-05, 3.8621036474379034e-05, 0.0, 0.9997989663970149, 2.2437885170264664e-05, 118.07497296419461, 339.0, 0.0, 7.883731791437955e-09, 0.0, 0.0, 0.0, 8.452743622880845e-07, 3.1549091281638227e-07, 0.0, 0.9999980760098343, 7.553411588403746e-07, 0.9682609609015458, 14899.0, 3701.0442543492163, 3.0770998885670858e-06, 0.0, 0.0, 0.0, 0.005637778320815311, 0.0020683849611638494, 0.0, 0.9919893666273644, 0.0003013929907679243, 0.9682609609015458, 14899.0, 20144.431074056873, 0.00026934421810636085, 0.0, 0.0, 0.0, 0.6880915943717772, 0.22951150255725855, 0.0, 0.048305066966824295, 0.03382249188603368, 3.556080711556774, 1862.0, 3664.5045684449683, 5.462834185500617e-07, 0.0, 0.0, 0.0, 0.0006090442050618982, 0.00027414551786862596, 0.0, 0.9990761455117988, 4.0118481852120566e-05, 118.07497296419461, 339.0, 1046.1989950752143, 7.883731684429637e-09, 0.0, 0.0, 0.0, 8.452743366674768e-07, 3.154909044639701e-07, 0.0, 0.9999980760098806, 7.553411466100165e-07, 3.556080711556774, 1862.0, 36.53968590424776, 0.0002568884911680373, 0.0, 0.0, 0.0, 0.5099611922921669, 0.182009686429065, 0.0, 0.28126805211964645, 0.026504180667953545, 14.7, 339.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 39.978851680317064, 2600.0, 54.6696053557629, 2.7872468755903984e-07, 4.6211254985288704e-05, 0.0, 0.0, 9.284051386163e-05, 3.737216494467455e-05, 0.0, 0.9998010497914028, 2.224755011803183e-05, 62.65598411254905, 1951.0, 84.21480298003588, 1.8371209405772942e-07, 0.0019518840960513495, 0.0, 0.0, 0.0002600216873928829, 0.00019878568811364862, 0.0, 0.9975728234819192, 1.6301334428798956e-05, 158.6828593491157, 1962.0, 157.76947832970882, 1.4800653258958544e-09, 0.813610690472183, 0.0, 0.0, 0.0001066246849427458, 9.315855136575117e-05, 0.0, 0.18618853254802314, 9.92263420054324e-07, 211.81375314428948, 1962.0, 130.00056832798225, 2.2446692029929896e-43, 0.9998215570133311, 0.0, 0.0, 9.692042758700843e-31, 9.890906236641041e-31, 0.0, 0.00017844298666891832, 9.832143825149989e-31, 47.65813528043452, 4100.0, 157.76947832970882, 1.4800653258958542e-09, 0.8136106904721829, 0.0, 0.0, 0.00010662468494274579, 9.315855136575116e-05, 0.0, 0.18618853254802312, 9.922634200543237e-07, 38.0, 4099.0, 129.99850431635835, 8.844541570379368e-31, 0.9999110083917484, 0.0, 0.0, 8.356036475680183e-31, 8.710802069418644e-31, 0.0, 8.89916082517079e-05, 9.854157322085815e-31, -4.696666208863519, 4100.0, 407.2431948538662, 0.0002677241777968503, 5.013099193457455e-44, 0.0, 0.0, 0.669626313607013, 0.22502167614545668, 0.0, 0.07211099225804704, 0.03297329381168649, 359.99985574726634, 15252.17212212109, 27524.23260007846, 0.00019754136650067616, 0.0, 0.0, 0.0, 0.7048414885540643, 0.2350807007683599, 0.0, 0.03508574242040018, 0.024794526890674892, 29.845, 14992.17212212109, 23845.47532840609, 0.00022801703236441224, 0.0, 0.0, 0.0, 0.5821682802013423, 0.19421017046061848, 0.0, 0.19477383335025647, 0.02861969895541827, 1.0, 14952.17212212109, 23845.475328406086, 0.00022801703236441227, 0.0, 0.0, 0.0, 0.5821682802013424, 0.1942101704606185, 0.0, 0.1947738333502565, 0.028619698955418275]\n",
      "[[0, 1524.3442442421804], [0.45155796027688455, 0.49909037714813564], [7424.154999999992, 7814.899999999991]]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 12000/12000 [2:32:27<00:00,  1.31it/s] \n"
     ]
    }
   ],
   "source": [
    "file_name = 'sim_files/demo01_100_dataset.usc'\n",
    "outputs_cell = [\"1\",\"15\",\"56\",\"60\",\"51\",\"53\",\"72\",\"HMB54\",\"41\",\n",
    "                \"42\",\"HMB57\",\"62\",\"*RCY\",\"32-2\",\"31\",\"32\",\"16\",\n",
    "                \"29\",\"26\",\"33\",\"27\",\"32-\",\"63\",\"20-2-2\",\"5-3\",\n",
    "                \"3-2\",\"6-2\",\"33-2\",\"35\",\"34\",\n",
    "                \"11\",\"23\",\"49\",\n",
    "                ]\n",
    "recover_init()\n",
    "inputs,outputs = gen_data(3,12000,initial_input_value)\n",
    "save_data(inputs,outputs,['data_100%_in.csv','data_100%_out.csv'])"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "9e192e4b83075e3ddca6984e464aed66f2cf89325ff1b87b1a375e27388972c7"
  },
  "kernelspec": {
   "display_name": "Python 3.10.4 ('dejavu')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
